﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Aij1.Utils;
using Aij1.Model;

namespace Aij1
{
    /// <summary>
    /// ShoppingItems 的摘要说明
    /// </summary>
    public class ShoppingItems : IHttpHandler, IRequiresSessionState
    {
        List<TempItems> tempShoppingItems;
        HttpContext Context;
        public void ProcessRequest(HttpContext context)
        {
            Context = context;
            tempShoppingItems = context.Session["ShoppingCart"] as List<TempItems>;
            if (tempShoppingItems == null)
            {
                tempShoppingItems = new List<TempItems>();
                context.Session["ShoppingCart"] = tempShoppingItems;
            }
            int oid = CommOp.ToInt(context.Request.QueryString["ID"]);
            int count = CommOp.ToInt(context.Request.QueryString["Count"]);
            if (oid <= 0)
            {
                WriteShoppingItemResult();
                return;
            }
            B_Series series = XpoHelper.GetNewSession().GetObjectByKey<B_Series>(oid);
            if (series == null)
            {
                WriteResponse("没有该商品的信息。");
                return;
            }

            var existItem = tempShoppingItems.FirstOrDefault(item => item.Oid == oid);
            if (existItem != null)
            {
                existItem.Count += count;
                if (existItem.Count == 0)
                {
                    tempShoppingItems.Remove(existItem);
                }
            }
            else
            {
                tempShoppingItems.Add(new TempItems()
                {
                    Oid = oid,
                    Count = count,
                    Price = series.Price,
                    Name = series.Title,
                });
            }

            WriteShoppingItemResult();
        }

        void WriteShoppingItemResult()
        {
            string result = String.Join("|", tempShoppingItems.Select(item => string.Format("{0};{1};{2};{3}",
              item.Oid, item.Name, item.Price, item.Count)).ToArray());
            WriteResponse(result);
        }

        void WriteResponse(object content)
        {
            Context.Response.Cache.SetNoStore();
            Context.Response.Clear();
            Context.Response.ContentType = "text/plain";
            Context.Response.Write(content);
            Context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }


    [Serializable]
    public class TempItems
    {
        public int Oid;
        public string Name;
        public int Price;
        public int Count;
        public Guid OrderId = Guid.NewGuid();
    }

}